<template>
  <main role="main">
    <div class="header-nav">
      <div class="clearfix">
        <div class="container">
          <div class="row">
            <div class="col-12">
              <a v-on:click="foldSwitchStatus = !foldSwitchStatus" style="cursor: pointer">
                <span v-show="foldSwitchStatus">▲</span>
                <span v-show="!foldSwitchStatus">▼</span>
              </a>
              <a v-on:click="onClickLevel1(0)" id="category-0" href="javascript:;" class="cur">全部</a>
              <a v-for="o in level1" :key="o" v-on:click="onClickLevel1(o.problemCategoryId)" v-bind:id="'category-' + o.problemCategoryId" href="javascript:;">{{o.problemCategoryName}}</a>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="skill clearfix" v-show="foldSwitchStatus">
      <div class="container">
        <div class="row">
          <div class="col-12">
            <a v-on:click="onClickLevel2(11111111)" id="category-11111111" href="javascript:;" class="on">不限</a>
            <a v-for="o in level2" :key="o" v-on:click="onClickLevel2(o.problemCategoryId)" v-bind:id="'category-' + o.problemCategoryId" href="javascript:;">{{o.problemCategoryName}}</a>
            <div style="clear:both"></div>
          </div>
        </div>
      </div>
    </div>

    <div class="album py-4 bg-light">

      <div class="container">

        <div>

          <div class="card mb-4 shadow-sm">
            <br>

            <el-row>
              <el-col :span="1">

              </el-col>
              <el-col :span="6">
                <label>试题难度</label>
              </el-col>

              <el-col :span="1">

              </el-col>

              <el-col :span="7">
                <label>试题名称</label>
              </el-col>
              <el-col :span="2">

              </el-col>
            </el-row>

            <el-row>

              <el-col :span="1">

              </el-col>


              <el-col :span="6">
                <el-select v-model="tagId" placeholder="试题难度" >
                  <el-option
                      @click="searchByTag(1)"
                      v-for="item in PROBLEM_TAG_SLUGS"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-col>

              <el-col :span="1" v-if="loginMember.userGroupId === USER_GROUP.Administrators.key">

              </el-col>

              <el-col :span="6" v-if="loginMember.userGroupId === USER_GROUP.Administrators.key">

                <el-select v-model="isPublic" placeholder="Select">
                  <el-option
                      v-for="item in YES_NO"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-col>

              <el-col :span="1"></el-col>


              <el-col :span="7">
                <el-input v-model="keyword" placeholder="Please input keyword" />

              </el-col>

              <el-col :span="2">
                <el-button style="margin-left: 10px" type="primary" @click = "list(1)">
                  <el-icon>
                  <span>搜索</span>
                  </el-icon>
                </el-button>

              </el-col>

              <el-col :span="2">
                <el-button style="margin-left: 10px" type="primary" @click = "creatObject">
                  创建
                </el-button>

              </el-col>
            </el-row>

            <br>

            <el-table
                :data="problems"
                stripe
                style="width: 100%"

            >
              <el-table-column width="60" prop="userSubmitResult">
                <template #default="scope">
<!--                  <span v-bind:class="{'success' : scope.row.userSubmitResult === '1',-->
<!--                                        'danger' : (scope.row.userSubmitResult === SUBMISSION_RESULT.CE.key || scope.row.userSubmitResult === SUBMISSION_RESULT.WA.key),-->
<!--                                        'warning' : (scope.row.userSubmitResult !== SUBMISSION_RESULT.CE.key && scope.row.userSubmitResult !== SUBMISSION_RESULT.AC.key-->
<!--                                        && scope.row.userSubmitResult !== SUBMISSION_RESULT.WA.key)}">-->
<!--                        {{scope.row.userSubmitResult}}-->
<!--                  </span>-->
                  <span v-bind:class="{'success' : scope.row.userSubmitResult === '1',
                                        'danger' : (scope.row.userSubmitResult === SUBMISSION_RESULT.CE.key || scope.row.userSubmitResult === SUBMISSION_RESULT.WA.key),
                                        'warning' : (scope.row.userSubmitResult !== SUBMISSION_RESULT.CE.key && scope.row.userSubmitResult !== SUBMISSION_RESULT.AC.key
                                        && scope.row.userSubmitResult !== SUBMISSION_RESULT.WA.key)}">
                        {{scope.row.userSubmitResult}}
                  </span>
                </template>
              </el-table-column>
              <el-table-column  label="类型" width="80">
                <template #default="scope" >
                  <span v-show="scope.row.questionType==='2'" class="success" >单选题</span>
                  <span v-show="scope.row.questionType==='3'" class="warning">多选题</span>
                  <span v-show="scope.row.questionType==='4'" class="danger">判断题</span>
                </template>
              </el-table-column>
              <el-table-column prop="title" label="题目" width="180" show-overflow-tooltip> </el-table-column>
              <el-table-column prop="categoryName" label="分类" width="100" show-overflow-tooltip> </el-table-column>
              <el-table-column  label="标签" width="80">
                <template #default="scope" >
                  <span v-bind:class="{'error' :  parseInt(scope.row.tagId) === PROBLEM_TAG_SLUGS[1].value,
                                        'danger' : parseInt(scope.row.tagId) === PROBLEM_TAG_SLUGS[2].value,
                                        'warning' : parseInt(scope.row.tagId) === PROBLEM_TAG_SLUGS[3].value,
                                        'success' : parseInt(scope.row.tagId) === PROBLEM_TAG_SLUGS[4].value,
                                     }">
                    {{scope.row.tagName}}
                  </span>
                </template>
              </el-table-column>

              <el-table-column prop="content" label="答案选项" width="180" show-overflow-tooltip> </el-table-column>
              <el-table-column prop="answer" label="答案" width="80" show-overflow-tooltip> </el-table-column>
              <el-table-column prop="hint" label="提示" width="80" show-overflow-tooltip> </el-table-column>
              <el-table-column prop="companyName" label="所属公司" width="80" show-overflow-tooltip> </el-table-column>
              <el-table-column label="操作" width="260">
                <template #default="scope" >

                  <el-button :disabled="scope.row.companyName!=='京东'"  type="warning" @click="handleEdit(scope.$index, scope.row)"
                  >编辑</el-button>
                  <el-button
                      :disabled="scope.row.companyName!=='京东'"
                      v-if="scope.row.disabled===0"
                      type="danger"
                      @click="Forbidden(scope.$index, scope.row)"
                  >禁用</el-button>
                  <el-button
                      v-else="scope.row.disabled===0"
                      type="success"
                      @click="unForbidden(scope.$index, scope.row)"
                  >解禁</el-button>
                </template>
              </el-table-column>

            </el-table>
            <br>
            <div id="problem-list-pagination">

              <pagination ref="pagination" v-bind:list="list" v-bind:itemCount="4"></pagination>
            </div>

          </div>

          <!--          <h3 v-show="courses.length === 0">暂无此类试题</h3>-->
        </div>

        <br>

      </div>
    </div>


  </main>
</template>

<script>
import Pagination from "./Pagination_1.vue";
import {Search} from '@element-plus/icons-vue/dist/index.min'
import API from '../api/trainer/questionManager'
export default {
  components: {Pagination, Search},
  name: 'the-problem-list',
  props: {

  },

  data: function () {
    return {
      foldSwitchStatus: false,
      optionWidth: 180,
      categoryId:0,
      tagId:"All",
      creatOrEdit:false,
      level1: [],
      level2: [],
      categorys: [],

      totalCount:0,
      currentPage:1,
      pageSize:10,

      level1Id: 0,
      level2Id: 0,
      problems: [],
      problemCategoryId: 0,
      keyword: "",
      problemTagSlug: 0,
      isPublic: "Yes",
      PROBLEM_TAG_SLUGS: PROBLEM_TAG_SLUGS,
      YES_NO: YES_NO,
      loginMember: {},
      USER_GROUP: USER_GROUP,
      SUBMISSION_RESULT: SUBMISSION_RESULT,
      SERVER_DOMAIN: SERVER_DOMAIN,
      CURRENT_ObjectivePROBLEM_LIST_PAGE: CURRENT_ObjectivePROBLEM_LIST_PAGE,
    }
  },

  mounted() {
    let _this = this;
    _this.$refs.pagination.size = 8;
    _this.loginMember = Tool.getLoginMember();
    if(_this.loginMember.userGroupId === USER_GROUP.Administrators.key) {
      _this.optionWidth = 240;
    }
    _this.allCategory()
    let currentPage = LocalStorage.get(CURRENT_ObjectivePROBLEM_LIST_PAGE) || 1;
    _this.list(currentPage);
    // _this.list();
  },

  methods: {
    initProblems(records){
      this.problems = records;
      this.problems.forEach(e=> {
        let content = ''
        let answerContent = ''
        let data = e.itemList
        data.forEach(r => {
          content += r.content + ','
          if (r.answer) {
            answerContent = r.content
          }
        })
        e.content = content
        e.answer = answerContent
      })

    },
    handleDoProblem(pid, row) {
      LocalStorage.set(CURRENT_PROBLEM, row);
      this.$router.push({
        path:'/question',
        query: {
          questionCount:this.totalCount
        }
      })

    },


    handleEdit(index, row) {

      LocalStorage.set(CURRENT_EDIT_PROBLEM, row);

      this.$router.push({
        path: "/training/objectQuestion",
      });

    },

      Forbidden(index, row) {

      let _this = this;

      Confirm.show("Are You Sure To Forbidden Problem " + row.problemId + " ?", function () {
        let param = {}
        let token = localStorage.getItem('token')
        param = row
        param.disabled = 1
        param.item = row.itemList
        let substrings = param.categoryId.split(',')
        let str = param.tagId.split(',')
        let categoryId = JSON.stringify(substrings.map(substring => parseInt(substring)))
        let tagId = JSON.stringify(str.map(substring => parseInt(substring)))

        param.categoryId =categoryId
        param.tagId = tagId
        API.createObject(param,token).then((res) => {
          Loading.hide();
          if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
            _this.$router.push({path: '/home'});
            return;
          }
          if (res.data.success) {
            _this.$notify.success("Forbidden Problem " + row.problemId + " Success...");
            setTimeout(function (){window.location.reload(true)},1000)
          }
        }).catch((err) => {
          Loading.hide();
          console.log(err);
        });
      });


    },

    unForbidden(index,row){

      var param = Object.assign({}, row)
      let _this = this;

      Confirm.show("Are You Sure To unForbidden Problem " + row.problemId + " ?", function () {

        let token = localStorage.getItem('token')

        param.disabled = 0
        param.item = row.itemList
        let substrings = param.categoryId.split(',')
        let str = param.tagId.split(',')
        let categoryId = JSON.stringify(substrings.map(substring => parseInt(substring)))
        let tagId = JSON.stringify(str.map(substring => parseInt(substring)))

        param.categoryId =categoryId
        param.tagId = tagId
        console.log(param)
        API.createObject(param,token).then((res) => {
          Loading.hide();
          if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
            _this.$router.push({path: '/home'});
            return;
          }
          if (res.data.success) {
            _this.$notify.success("unForbidden Problem " + row.problemId + " Success...");
            setTimeout(function (){window.location.reload(true)},1000)
          }
        }).catch((err) => {
          Loading.hide();
          console.log(err);
        });
      });

    },

    setQueryCondition(problemCategoryId, keyword) {
      this.categoryId = problemCategoryId;
      this.keyword = keyword;
    },


    search() {
      let param = {}
      param.size = 10
      param.current = 1
      this.categoryId = 0
      this.tagId = 0
      param.title = this.keyword
      // if(this.categoryId!==0){
      //   param.categoryId = this.categoryId
      // }
      // if(this.tagId!==0){
      //   param.tagId = this.tagId
      // }
      let token = localStorage.getItem('token')
      API.objectiveList(param, token).then(res => {
        this.initProblems(res.data.content.records)
        this.totalCount = res.data.content.total
      }).catch(e => {
        console.log(e)
      })
    },

    searchByTag(page){
      let _this = this;
      let param = {}
      // param.size = this.pageSize
      // param.current = this.currentPage
      param.size = _this.$refs.pagination.size
      param.current = page
      if(this.tagId!=0) {
        param.tagId = _this.tagId
      }
      if(this.categoryId!==0){
        param.categoryId = _this.categoryId
      }
      let token = localStorage.getItem('token')
      API.objectiveList(param,token).then(res=>{
       this.initProblems(res.data.content.records)
        this.totalCount = res.data.content.total
        if (res.data) {
          this.totalCount = res.data.content.total
          _this.$refs.pagination.render(page, res.data.content.total);
        }
      }).catch(e=>{
        console.log(e)
      })
    },

    /**
     * 题目查询
     *
     */
    list(page) {

      let _this = this;
      LocalStorage.set(CURRENT_ObjectivePROBLEM_LIST_PAGE, page);
      let params={}
      let token = localStorage.getItem('token')
      params.current = page
      params.size =_this.$refs.pagination.size
      params.title = _this.keyword
      if(this.categoryId!==0){
        params.categoryId = this.categoryId
      }
      if(this.tagId!==0){
        params.tagId = this.tagId
      }
      API.objectiveList(params,token).then((res) => {
        Loading.hide();
        console.log(res.data)
        if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
          _this.$router.push({path: '/home'});
          return;
        }
        if (res.data) {
          this.initProblems(res.data.content.records)
          this.totalCount = res.data.content.total
          this.$refs.pagination.render(page, res.data.content.total);
          // _this.problems = res.data.content.records;
          // _this.problems.forEach(e=>{
          //   let content = ''
          //   let answerContent = ''
          //   let data = e.itemList
          //   data.forEach(r=>{
          //     content+=r.content+','
          //     if(r.answer){
          //       answerContent = r.content
          //     }
          //   })
          //   e.content = content
          //   e.answer = answerContent
          // })
          //
          // console.log(_this.problems)
          this.totalCount = res.data.content.total
        }
      }).catch((err) => {
        Loading.hide();
        console.log(err);
      });


    },

    /**
     * 所有分类查询
     */
    allCategory() {
      let _this = this;
      let token = localStorage.getItem('token')
      API.questionCategoryList(token).then((res) => {
        if(res.data.success) {
          _this.categorys = res.data.content;
          // 将所有记录格式化成树形结构
          _this.level1 = [];
          for (let i = 0; i < _this.categorys.length; i++) {
            let c = _this.categorys[i];
            if (c.problemCategoryParentId === 0) {
              _this.level1.push(c);
            } else {
              _this.level2.push(c);
            }
          }

        }
      }).catch((err) => {
        console.log(err);
      });


    },

    /**
     * 点击一级分类时
     * @param level1Id
     */
    onClickLevel1(level1Id) {
      let _this = this;

      // 点击一级分类时，设置变量，用于课程筛选
      // 二级分类id为空，
      // 如果点击的是【全部】，则一级分类id为空
      _this.level2Id = null;
      _this.level1Id = level1Id;


      // 点击一级分类时，显示激活状态
      $("#category-" + level1Id).siblings("a").removeClass("cur");
      $("#category-" + level1Id).addClass("cur");

      // 点击一级分类时，二级分类【无限】按钮要设置激活状态
      $("#category-11111111").siblings("a").removeClass("on");
      $("#category-11111111").addClass("on");

      // 注意：要先把level2中所有的值清空，再往里放
      _this.level2 = [];
      let categorys = _this.categorys;
      // 如果点击的是【全部】，则显示所有的二级分类
      if (level1Id === 0) {
        for (let i = 0; i < categorys.length; i++) {
          let c = categorys[i];
          if (c.problemCategoryParentId !== 0) {
            _this.level2.push(c);
          }
        }
      }
      // 如果点击的是某个一级分类，则显示该一级分类下的二级分类
      if (level1Id !== 0) {
        for (let i = 0; i < categorys.length; i++) {
          let c = categorys[i];
          if (c.problemCategoryParentId === level1Id) {
            _this.level2.push(c);
          }
        }
      }
      _this.setQueryCondition(_this.level1Id, "");
      _this.list(1);
      // 重新加载课程列表
      //_this.listCourse(1);
    },

    /**
     * 点击二级分类时
     * @param level1Id
     */
    onClickLevel2(level2Id) {
      let _this = this;
      $("#category-" + level2Id).siblings("a").removeClass("on");
      $("#category-" + level2Id).addClass("on");

      // 点击二级分类时，设置变量，用于课程筛选
      // 如果点击的是【无限】，则二级分类id为空
      if (level2Id === 11111111) {
        _this.level2Id = _this.level1Id;
      } else {
        _this.level2Id = level2Id;
      }

      _this.setQueryCondition(_this.level2Id, "");
      _this.list(1);

      // 重新加载课程列表
      //_this.listCourse(1);
    },
    creatObject(){
      localStorage.removeItem('CURRENT_EDIT_PROBLEM')
      this.$router.push({
        path:'/training/objectQuestion'
      })

    },
    //TODO
    // 不知道这里的2个list是什么作用，默认加上了list(val)，因为list中要加参数
    // 伍先康
    CurrentChange(val){
      this.currentPage =val
      this.list(val)
    },
    SizeChange(val){
      this.pageSize = val
      this.list(val)
    },

  },

}
</script>

<style scoped>
#problem-list-pagination {
  padding-left: 20px;
}

/* 头部 一级分类 */
.header-nav {
  height: auto;
  background: #fff;
  box-shadow: 0 8px 16px 0 rgba(28,31,33,.1);
  padding: 16px 0;
  box-sizing: border-box;
  position: relative;
  z-index: 1;
  /*background-color: #d6e9c6;*/
}
.header-nav>div {
  width: 100%;
  padding-left: 12px;
  box-sizing: border-box;
  margin-left: auto;
  margin-right: auto;
  /*background-color: #B4D5AC;*/
}
.header-nav a {
  float: left;
  font-size: 16px;
  color: #07111b;
  line-height: 50px;
  height: 45px;
  position: relative;
  margin-right: 46px;
  font-weight: 700;
}
.header-nav a:hover {
  color: #c80;
}
.header-nav a.cur {
  color: #c80;
}
.header-nav a.cur:before {
  display: block;
}
.header-nav a:before {
  display: none;
  content: ' ';
  position: absolute;
  bottom: 0;
  background: #c80;
  width: 16px;
  height: 3px;
  left: 50%;
  margin-left: -8px;
}
/* 二级分类 */
.skill {
  width: 100%;
  padding: 24px 0 0;
  position: relative;
  margin: 0 auto;
}
.skill a.on {
  color: #c80;
  background: rgba(204,136,0,.1);
}
.skill a {
  float: left;
  margin-right: 20px;
  padding: 0 12px;
  font-size: 14px;
  color: #4d555d;
  line-height: 32px;
  border-radius: 6px;
  margin-bottom: 12px;
}
.skill a:hover {
  background: #d9dde1;
}

label {
  font-weight: bold;
}

.success {
  color: #67c23a;
}

.warning {
  color: #ffc107;
}

.danger {
  color: #db6f6e;
}

.error {
  color: #ff0400;
}
</style>
